/**
 * Created by hsia on 2017/4/12.
 * 按单位时段收费
 */
var unitTimeChargeJs = function(targetObj){
    this.sysUtils = new kendoUtils();
    this.targetObj = targetObj;
    this.init();
    return this;
};

var standardBinfo = function(id, $list) {
    if (id == undefined || !id) {
        this.id = "d-" + new Date().getTime();
    } else {
        this.id = id;
    }
    this.$list = $list;
    return this;
}
standardBinfo.prototype = {
    addToList : function($p) {
        $p.createTr(this.$list.find("tbody"));
    }
}
unitTimeChargeJs.prototype={
    init:function(){
        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var bindFunctionArray = [
            {fName:"savechargeInfo",fs:this.savechargeInfo},
            {fName:"cancel",fs:function(){$("#"+tempchargeList.monthChargeDivId).data("kendoWindow").close();}},
            {fName:"createRow",fs:this.createRow},
            {fName:"deleteRow",fs:this.deleteRow}];
        this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
        this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
        this.targetObj.find(":radio[name='dailyCap']").click(this.clickRadio);
        this.targetObj.find(":radio[name='thresholdCap']").click(this.clickRadio);
        var times = Utils.getModelValueByModelKey(BASIS.CHARGE_TIME_TYPE.DAY);
        Utils.createDataDictDropDownList([{div:this.targetObj.find("#billableHoursGroup"),parentModelKey:BASIS.CHARGE_TIME_TYPE.ROOT,select:times,change:this.chargeTypechange}],this);
        this.targetObj.find('.tableDiv').hide();
        this.loadChargeInfo()
    },
    //保存收费标准信息
    savechargeInfo:function(e){
        var that =  $(e.target).data("that");
        if(validityForm(that.targetObj)){
            var chargeInfo = that.sysUtils.getBindDocJson();
            var url = baseApiPath+"chargeStandard/save?isEdit=" + tempchargeList.isEdit;
            var sendJson=chargeInfo;
            for(var o in chargeInfo){
                if(o.indexOf('_') !=-1){
                    var strArray = o.substring(o.indexOf('_')+1);
                    var name = o.substring(0, o.indexOf('_'));
                    var jsonA = {};
                    jsonA[name] = that.recursionObjectName(strArray,chargeInfo[o]) ;
                    delete chargeInfo[o];
                    var sendJson =$.extend(true,chargeInfo,jsonA);
                }
            }
            //封装封顶组别数据
            var jsonE = {chargeStandardInfos:{A:{}}};
            that.targetObj.find(":radio[name='dailyCap']").each(function () {
                if(this.checked){
                    var id = this.id;
                    if(id=='' || id == undefined){
                        jsonE.chargeStandardInfos.A["dailyCapMoney"] = '-1';
                        jsonE.chargeStandardInfos.A["dailyCapTime"] = '-1';
                    }else if(id == 'Money'){
                        jsonE.chargeStandardInfos.A["dailyCapTime"] = '-1';
                    }else if(id == 'Time'){
                        jsonE.chargeStandardInfos.A["dailyCapMoney"] = '-1';
                    }
                    sendJson = $.extend(true,sendJson,jsonE);
                }
            });
            that.targetObj.find(":radio[name='thresholdCap']").each(function () {
                if(this.checked){
                    var id = this.id;
                    if(id=='' || id == undefined){
                        jsonE.chargeStandardInfos.A["thresholdMoney"] = '-1';
                    }
                    sendJson = $.extend(true,sendJson,jsonE);
                }
            });
            var flag = true;
            //封装列表数据
            var billableHours = sendJson.chargeStandardInfos.A.billableHoursGroup;
            if(billableHours && billableHours == '1'){
                var jsonD= {chargeStandardInfos:{B:{}}};
                that.targetObj.find("#standard-list > tbody tr").each(function (inx, itm) {
                    var cols = $(itm).find("td");
                    var bg = $(cols[1]).find("input").val();
                    var ed = $(cols[2]).find("input").val();
                    var jgsj = $(cols[3]).find("input").val();
                    var jgje = $(cols[4]).find("input").val();
                    if(bg && ed && jgsj && jgje){
                        jsonD.chargeStandardInfos.B["array"+inx] = JSON.stringify({beginTime:bg,endTime:ed,intervalChargingMoney:jgsj,intervalChargingTime:jgje});
                    }else{
                        notification({ title:"验证失败",message:"列表项不能留空"},'info');
                        flag = false;
                    }

                });
                //合并json对象
                sendJson = $.extend(true,sendJson,jsonD);
            }
            if(!tempchargeList.isEdit){
                sendJson["chargeType"]=1;
                sendJson["chargeParamCode"]='unitTime';
            }
            if(!flag){
                return;
            };
            JsonpAjax(url,JSON.stringify(sendJson),"json",function(result){
                $("#"+tempchargeList.monthChargeDivId).data("kendoWindow").close();
                tempchargeList.findGridData();
            });
        }
    },
    recursionObjectName : function (strArray,val) {
        if (strArray.indexOf('_') == -1){
            var jsonC = {};
            jsonC[strArray]=val;
            return jsonC;
        }
        var name = strArray.substring(0, strArray.indexOf('_'));
        strArray = strArray.substring(strArray.indexOf('_')+1);
        var jsonB = {};
        jsonB[name] = this.recursionObjectName(strArray,val);
        return jsonB;
    },
    loadChargeInfo : function(e) {
        var that = this;
        if (!isEmpty(e)) {
            that = $(e.target).data("that");
        }
        debugger;
        var cumulativeWay = this.targetObj.find("#cumulativeWay");
        var wayA = Utils.getModelValueByModelKey(BASIS.CUMULATIVE_WAY.CUMULATIVE_WAY_A);
        Utils.createDataDictDropDownList([{div:cumulativeWay,parentModelKey:BASIS.CUMULATIVE_WAY.ROOT,select:wayA}],this);
        var freeOvertimeBiling = this.targetObj.find("#freeOvertimeBiling");
        var biling = Utils.getModelValueByModelKey(BASIS.BOTT_LEVEL_ROOT.BOTT_LEVEL_N);
        Utils.createDataDictDropDownList([{div:freeOvertimeBiling,parentModelKey:BASIS.BOTT_LEVEL_ROOT.ROOT,select:biling}],this);
        var freePreferentialWay = this.targetObj.find("#freePreferentialWay");
        var ferentialWay = Utils.getModelValueByModelKey(BASIS.FREE_PREFERENTIAL_WAY.FREE_PREFERENTIAL_WAY_D);
        Utils.createDataDictDropDownList([{div:freePreferentialWay,parentModelKey:BASIS.FREE_PREFERENTIAL_WAY.ROOT,select:ferentialWay}],this);
        var cumulativeType =  Utils.getModelValueByModelKey(BASIS.CUMULATIVE_TYPE.CUMULATIVE_TYPE_A);
        Utils.createDataDictDropDownList([{div:this.targetObj.find("#cumulativeType"),parentModelKey:BASIS.CUMULATIVE_TYPE.ROOT,select:cumulativeType}],this);
        if(null == tempchargeList.editResult) return; //新增啥都不需要做
        this.sysUtils.setVariantBindFieldValue(tempchargeList.editResult);
        that.showOff();
        that.chargeStandardInfos = tempchargeList.editResult.chargeStandardInfos;
        var basic = that.chargeStandardInfos.A;
        var money=basic.dailyCapMoney,time=basic.dailyCapTime,thresholdMoney=basic.thresholdMoney;
        if(money=='-1'&&time=='-1'){
            that.targetObj.find(":radio[name='dailyCap']")[0].checked = true;
            that.targetObj.find('#dailyCapMoney').prop('disabled',true);
            that.targetObj.find('#dailyCapTime').prop('disabled',true);
        }else if(money!='-1'&&time=='-1'){
            that.targetObj.find(":radio[name='dailyCap']")[1].checked = true;
            that.targetObj.find('#dailyCapMoney').prop('disabled',false);
        }else if(money=='-1'&&time!='-1'){
            that.targetObj.find(":radio[name='dailyCap']")[2].checked = true;
            that.targetObj.find('#dailyCapTime').prop('disabled',false);
        }
        if(thresholdMoney=='-1'){
            that.targetObj.find(":radio[name='thresholdCap']")[0].checked = true;
            that.targetObj.find('#thresholdMoney').prop('disabled',true);
        }else{
            that.targetObj.find(":radio[name='thresholdCap']")[1].checked = true;
            that.targetObj.find('#thresholdMoney').prop('disabled',false);
        }
        var arrayinfo = that.chargeStandardInfos.B;
        if(isEmpty(arrayinfo)) return;
        var l = Object.getOwnPropertyNames(arrayinfo).length;
        if (arrayinfo && l < 1) {
            return;
        }
        for (var i = 0; i < l; i++) {
            var key = "array"+i;
            if(arrayinfo.hasOwnProperty(key)){
                var item = eval('(' + arrayinfo[key] + ')');
                that.createTr(that.targetObj.find("#standard-list > tbody"),i,item);
            }

        }

    },
    createTr : function($tbody, id,item) {
        var _this = this;
        var tr = document.createElement("tr");
        var td_check = document.createElement("td");
        var td_BeginTime = document.createElement("td");
        var td_EndTime = document.createElement("td");
        var td_intervalChargingTime = document.createElement("td");
        var td_intervalChargingMoney = document.createElement("td");

        var checkbox = document.createElement("input");
        checkbox.value = id;
        checkbox.tabindex = -1;
        checkbox.type = "checkbox";
        checkbox.name = "standard_ids";
        td_check.appendChild(checkbox);

        var beginTime = document.createElement("input");
        beginTime.type = "text";
        beginTime.value = item == undefined ? '' : item["beginTime"] == undefined ? '' : item["beginTime"];
        beginTime.placeholder = "点我填写";
        beginTime.name = "beginTime";
        beginTime.setAttribute('data-validate','number');
        beginTime.setAttribute('validationMessage','请输入有效时间,格式:13:30');
        beginTime.pattern = "^([01]\\d|2[01234]):([0-5]\\d|60)$";
        beginTime.required = true;
        td_BeginTime.appendChild(beginTime);

        var endTime = document.createElement("input");
        endTime.type = "text";
        endTime.value = item == undefined ? '' : item["endTime"] == undefined ? '' : item["endTime"];
        endTime.placeholder = "点我填写";
        endTime.name = "endTime";
        endTime.setAttribute('data-validate','number');
        endTime.setAttribute('validationMessage','请输入有效时间,格式:13:30');
        endTime.pattern = "^([01]\\d|2[01234]):([0-5]\\d|60)$";
        endTime.required = true;
        td_EndTime.appendChild(endTime);

        var intervalChargingTime = document.createElement("input");
        intervalChargingTime.type = "text";
        intervalChargingTime.value = item == undefined ? '' : item["intervalChargingTime"] == undefined ? '' : item["intervalChargingTime"];
        intervalChargingTime.placeholder = "点我填写时长,单位/分钟";
        intervalChargingTime.name = "intervalChargingTime";
        intervalChargingTime.setAttribute('data-validate','number');
        intervalChargingTime.setAttribute('validationMessage','请输入有效分钟数');
        intervalChargingTime.pattern = "^[1-9]\\d*$";
        intervalChargingTime.required = true;
        td_intervalChargingTime.appendChild(intervalChargingTime);



        var intervalChargingMoney = document.createElement("input");
        intervalChargingMoney.type = "text";
        intervalChargingMoney.value = item == undefined ? '' : item["intervalChargingMoney"] == undefined ? '' : item["intervalChargingMoney"];
        intervalChargingMoney.placeholder = "点我填写金额,单位/元";
        intervalChargingMoney.name = "intervalChargingMoney";
        intervalChargingMoney.setAttribute('data-validate','number');
        intervalChargingMoney.setAttribute('validationMessage','请输入有效金额');
        intervalChargingMoney.pattern = "^[0-9]+(\\.[0-9]{2})?$";
        intervalChargingMoney.required = true;
        td_intervalChargingMoney.appendChild(intervalChargingMoney);

        intervalChargingMoney.addEventListener('keydown', function(e) {
            if (e.keyCode == 9) {
                if ($(this).parents("tr").next().length < 1) {
                    var $_no_input = $(this).parents("tr").find("input[name=beginTime]");
                    var _val = $_no_input.val();
                    if (_val == "" || _val == undefined || !_val) {
                        e.returnValue = false;
                        e.cancel = true;
                        $_no_input.focus();
                        return;
                    }
                    e.returnValue = false;
                    e.cancel = true;
                    new standardBinfo(undefined, unitTimeCharge.targetObj.find("#standard-list")).addToList(_this);
                    unitTimeCharge.targetObj.find("#standard-list tbody tr:last input[name=beginTime]").focus();
                    return;
                }
            }
        });
        tr.appendChild(td_check);
        tr.appendChild(td_BeginTime);
        tr.appendChild(td_EndTime);
        tr.appendChild(td_intervalChargingTime);
        tr.appendChild(td_intervalChargingMoney);
        $tbody[0].appendChild(tr);
    },
    deleteRow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        _this.targetObj.find("input[name=\"standard_ids\"]:checked").each(function(inx, itm) {
            $(itm).parents("tr").remove();
        });
    },
    createRow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        new standardBinfo(undefined, unitTimeCharge.targetObj.find("#standard-list")).addToList(_this);
    },
    showOff:function () {
        var unitTimeDownList = $('#billableHoursGroup').data('kendoDropDownList');
        var flag = unitTimeDownList.dataItem(unitTimeDownList.select()).modelValue == '0' ? true : false;
        if(flag){
            $('.tableDiv').hide();
        }else{
            $('.tableDiv').show();
        }
    },
    chargeTypechange:function () {
        var flag = this.dataItem(this.select()).modelValue == '0' ? true : false;
        if(flag){
            $('.tableDiv').hide();
        }else{
            $('.tableDiv').show();
        }
    },
    clickRadio:function (e) {
        var id =this.id;
        if('dailyCap'==this.name){
            if(id=='' || id == undefined){
                $('#dailyCapMoney').prop('disabled',true);
                $('#dailyCapMoney').prop('required',false);
                $('#dailyCapTime').prop('disabled',true);
                $('#dailyCapTime').prop('required',false);
            }else if(id == 'Money'){
                $('#dailyCapMoney').prop('disabled',false);
                $('#dailyCapMoney').prop('required',true);
                $('#dailyCapTime').prop('disabled',true);
                $('#dailyCapTime').prop('required',false);
            }else if(id == 'Time'){
                $('#dailyCapTime').prop('disabled',false);
                $('#dailyCapTime').prop('required',true);
                $('#dailyCapMoney').prop('disabled',true);
                $('#dailyCapMoney').prop('required',false);
            }
        }else if('thresholdCap'==this.name){
            if(id=='' || id == undefined){
                $('#thresholdMoney').prop('disabled',true);
                $('#thresholdMoney').prop('required',false);
            }else {
                $('#thresholdMoney').prop('disabled',false);
                $('#thresholdMoney').prop('required',true);
            }
        }

    }
}